import { useGameStore } from '../stores/game';

// 后端 API 的基础 URL，稍后根据实际情况配置
// 可以考虑使用环境变量
const API_BASE_URL = '/api';

export const guessDrawing = async (imageDataUrl: string) => {
  const gameStore = useGameStore();
  gameStore.startGuessing(); // 触发 loading 和 guessing 状态

  try {
    const response = await fetch(`${API_BASE_URL}/guess`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ image: imageDataUrl }),
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ message: '请求失败，无法解析错误信息' }));
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
    }

    const result = await response.json();

    if (!result.guess) {
        throw new Error('API 返回无效，缺少猜测结果');
    }

    gameStore.setGuessResult(result.guess);
    return result.guess;

  } catch (error) {
    console.error('Guess API call failed:', error);
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    gameStore.setError(errorMessage);
    // 可以选择性地将错误再次抛出，让调用者也能处理
    // throw error;
  }
}; 